package com.desyang.server.net.impl;

import java.net.ServerSocket;
import java.net.Socket;

import com.desyang.server.net.RequestProcessor;
import com.desyang.server.net.RpcServer;
import com.desyang.server.provider.ServiceProvider;

public class RpcServerImpl implements RpcServer {

    private ServerSocket serverSocket = null;
    private ServiceProvider serviceProvider = null;

    public RpcServerImpl(ServiceProvider serviceProvider) {
        this.serviceProvider = serviceProvider;
    }

    @Override
    public void start(int port) throws Exception {
        serverSocket = new ServerSocket(port);

        while (true) {
            Socket socket = serverSocket.accept();

            new Thread(new RequestProcessor(serviceProvider, socket)).start();
        }
    }

    @Override
    public void stop() throws Exception {
        if (serverSocket != null) {
            serverSocket.close();
        }
    }
}
